﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using log4net;

namespace Klinkby.MicroBus.Service
{
    static class Program
    {
        readonly static ILog _log = LogManager.GetLogger(typeof(Program));

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            _log.Info("Starting service controller");
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => _log.Fatal(e.ExceptionObject);

            var servicesToRun = new ServiceBase[] 
			{ 
				new MicrobusService() 
			};
#if DEBUG
            if (Environment.UserInteractive)
            {
                Type type = typeof(ServiceBase);
                BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
                MethodInfo method = type.GetMethod("OnStart", flags);

                foreach (ServiceBase service in servicesToRun)
                {
                    method.Invoke(service, new object[] { args });
                }

                Console.WriteLine("Press <enter> key to exit");
                Console.ReadLine();
                Console.WriteLine("Stopping services");

                foreach (ServiceBase service in servicesToRun)
                {
                    service.Stop();
                }
                Console.WriteLine("Quitting");
            }                    
            else
#endif
                ServiceBase.Run(servicesToRun);
        }
    }
}
